package com.xudow.app.util;

import android.os.Environment;

import com.google.api.client.util.IOUtils;
import com.umeng.message.proguard.T;
import com.xudow.app.Config;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.List;

/**
 * Utilities and constants related to files
 */
public class FileUtils {

    /**
     * 获取SD卡数据文件根目录
     *
     * @return
     */
    public static String getDataPath() {
        String sdCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
        String path = sdCardRoot + File.separator + Config.SDCARD_ROOT_DIR + File.separator;

        initSDCardDirs(path);

        return path;
    }

    /**
     * 初始化sd卡目录
     */
    public static void initSDCardDirs(String rootPath) {
        File dirFile = new File(rootPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
    }

    public static void writeFile(String data, File file) throws IOException {
        writeFile(data.getBytes(Charset.forName("UTF-8")), file);
    }

    public static void writeFile(byte[] data, File file) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, false));
        bos.write(data);
        bos.close();
    }

    public static void writeFile(List<?> data,File file) throws IOException{
        ObjectOutputStream oos= new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(data);
        oos.close();
    }

    public static List<?> readFils(File file) throws ClassNotFoundException,IOException{
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
        List<?> data=(List <?>)ois.readObject();
        return data;

    }
    public static String readFileAsString(File file) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOUtils.copy(bis, bos);
        byte[] contents = bos.toByteArray();
        bis.close();
        bos.close();
        return new String(contents, Charset.forName("UTF-8"));
    }

}
